package com.dsz.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.dsz.entity.Users;
import com.dsz.service.UsersService;
import com.dsz.until.TokenUtil;
import com.fasterxml.jackson.core.JsonProcessingException;

@CrossOrigin
@RestController
public class LoginController {

	@Autowired
	private UsersService us;
	
	@GetMapping("/login")
	public Map<String, Object> login(Users u){
		Map<String, Object> map = new HashMap<>();
		//连接数据库查询
		u = us.login(u);
		System.out.println(u);
		if (u == null) {
			map.put("code", 0);
			return map;
		}//登录成功等待生成Token
		//生成Token
		String token = null;
		try {
			//工具类生成Token
			token = TokenUtil.sign(u, 1 * 60 * 60 * 1000); // 1 * 60 * 60 * 1000 = 1小时有效期
		} catch (UnsupportedEncodingException | JsonProcessingException e) {
			e.printStackTrace();
		}
		map.put("token", token);
		map.put("uid", u.getUid());
		map.put("loginname", u.getLoginname());
		//返回到前端页面
		return map;
	}
	
	//测试token是否有效
	@RequestMapping("/testToken")
	public Boolean testToken(){
		return true;
	}
}
